<template>
    <div class="common-layout">
        <el-container>
            <el-main>
                <!-- 按钮组件 -->
                <div class="btn">
                    <div class="inp">
                        <el-input placeholder="请输入商品名称" clearable v-model="datas.spuName" />
                    </div>
                    <div class="inp">
                        <el-input placeholder="请输入团购ID" clearable v-model="datas.id" />
                    </div>
                    <div class="inp">
                        <el-select v-model="datas.status" clearable class="m-2" placeholder="请选择团购状态">
                            <el-option v-for="item in groupStatusMap" :key="item.value" :label="item.name"
                                :value="item.value" />
                        </el-select>
                    </div>
                    <el-button type="primary" :icon="Search" @click="init">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
                </div>
                <!-- 表格组件 -->
                <div id="tab">
                    <el-table :data="groupData" border width="100%">
                        <el-table-column type="expand">
                            <!-- 子表格 -->
                            <template #default="props">
                                <!-- 描述列表组件 -->
                                <el-descriptions class="margin-top" :column="1" border>
                                    <el-descriptions-item label="类目ID">
                                        {{ props.row.categoryId }}
                                    </el-descriptions-item>
                                    <el-descriptions-item label=" 商品sku属性">
                                        <el-table :data="props.row.groupShopSkuDTOList" :border="childBorder">
                                            <el-table-column label="StuId" prop="skuId" align="center" width="150" />
                                            <el-table-column label="规格标题" prop="title" align="center" width="190" />
                                            <el-table-column label="团购价格(元)" prop="price" align="center" width="170" />
                                            <el-table-column label="库存" align="center" width="170">
                                                <template #default="scope">
                                                    {{ scope.row.stock }}(件)
                                                </template>
                                            </el-table-column>
                                            <el-table-column label="原始价格(元)" prop="originalPrice" align="center"
                                                width="170" />
                                            <el-table-column label="会员价格(元)" prop="vipPrice" align="center"
                                                width="170" />
                                        </el-table>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </template>
                        </el-table-column>
                        <!-- 页面主表格渲染 -->
                        <el-table-column prop="id" label="团购ID" align="center" width="80" />
                        <el-table-column prop="spuId" label="商品ID" align="center" width="100" />
                        <el-table-column prop="title" label="团购名称" align="center" width="150" />
                        <el-table-column label="商品主题" align="center" width="100px">
                            <!-- 悬停后显示的图片 -->
                            <template #default="scope">
                                <el-popover effect="light" trigger="hover" placement="top" width="24vw">
                                    <template #default>
                                        <span> <img :src="scope.row.img" style="width: 300px;" /></span>
                                    </template>
                                    <!-- 显示页面的图片 -->
                                    <template #reference>
                                        <span class="pic"> <img :src="scope.row.img" />
                                        </span>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="未满策略" align="center" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.automaticRefund == 1 ? 'success' : 'warning'">
                                    {{ scope.row.automaticRefund == 0 ? '发货' : '退款' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="活动状态" align="center" width="100">
                            <template #default="scope">
                                <el-tag>{{ scope.row.status == 1 ? '激活' : '冻结' }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtStart" label="开始时间" align="center" width="180" />
                        <el-table-column prop="gmtEnd" label="结束时间" align="center" width="180" />
                        <el-table-column prop="buyerNum" label="当前人数" align="center" width="100" />
                        <el-table-column prop="minNum" label="目标人数" align="center" width="100" />
                        <el-table-column label="操作" align="center" width="200">
                            <template #default="scope">
                                <!-- 判断当前状态是否为激活状态，否则隐藏 -->
                                <div v-if="scope.row.status == 0">
                                    <el-button type="primary" @click="handlEdit(scope.row)">编辑</el-button>
                                    <el-button type="danger" @click="handlDelt(scope.$index, scope.row)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页组件 -->
                <Pagination @page-change="handlePagehange" v-bind="datas" />
                <!-- 抽屉组件 -->
                <el-drawer v-model="drawer" direction="ltr" :show-close="false" size="52%">
                    <el-card class="box-card">
                        <template #header="{ titleId, titleClass }">
                            <div class="card-header">
                                <div>
                                    <h4 :id="titleId" :class="titleClass">{{ title }}团购商品</h4>
                                </div>
                                <div> <el-button @click="closeClick">取消</el-button>
                                    <el-button type="primary" @click="yes">确定</el-button>
                                </div>
                            </div>
                        </template>
                        <div class="content">
                            <el-form :model="form">
                                <el-form-item label="商品属性(spu)" :label-width="formLabelWidth"
                                    style="font-weight: bold;" />
                                <el-form-item label="团购商品" prop="spuId" label-width="140">
                                    <!-- 级联选择器组件 -->
                                    <el-cascader v-model="form.spuId" :options="productList" @change="changeDetails"
                                        :props="{ emitPath: false, label: 'label', value: 'id', children: 'children' }"
                                        placeholder="请选择" filterable clearable />
                                </el-form-item>
                                <el-form-item label="团购时间" :label-width="formLabelWidth">
                                    <!-- 日期时间选择器 -->
                                    <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="选择日期" />
                                    至
                                    <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="选择日期" />
                                </el-form-item>
                                <el-form-item label="团购基础人数" :label-width="167" prop="minNum">
                                    <!-- 数字输入框 -->
                                    <el-input-number v-model="form.minNum" class="mx-4" :min="1"
                                        controls-position="right" />
                                </el-form-item>
                                <el-form-item label="活动结束时人数没有" label-width="207">
                                    <el-radio-group v-model="form.automaticRefund" size="large">
                                        <el-radio-button :label="0">不退款,我要发货</el-radio-button>
                                        <el-radio-button :label="1">自动退款,我不发货</el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="达到基础人数采取:" :label-width="195"> </el-form-item>
                            </el-form>
                        </div>
                    </el-card>
                    <!-- 选择团购商品选项显示的详情列表 -->
                    <el-card class="box-card">
                        <template #header>
                            <div class="card-header">
                                <h3>商品类型(sku)</h3>
                                <div>
                                    <!-- 弹出层-->
                                    <el-popover :visible="visible" placement="top" :width="350">
                                        <p>
                                            <el-form :model="editGroupsForm">
                                                <el-form-item label="团购价格" :label-width="100">
                                                    <!-- 数字输入框 -->
                                                    <el-input-number v-model="editGroupsForm.num" class="mx-4" :min="1"
                                                        controls-position="right" />元
                                                </el-form-item>
                                            </el-form>
                                        </p>
                                        <div style="text-align: right; margin: 0">
                                            <el-button size="small" text @click="visible = false">取消</el-button>
                                            <!-- 批量定价确定按钮 -->
                                            <el-button size="small" type="primary" @click="groupPriceYes">确定</el-button>
                                        </div>
                                        <template #reference>
                                            <el-button @click="handlePrice">批量定价</el-button>
                                        </template>
                                    </el-popover>
                                </div>
                            </div>
                        </template>
                        <!-- 弹出商品详情列表 -->
                        <el-table :data="detailsData" width="100%">
                            <el-table-column prop="barCode" label="sku条形码" align="center" width="150" />
                            <el-table-column prop="title" label="类型名" align="center" width="160" />
                            <el-table-column prop="stock" label="库存" align="center" width="100" />
                            <el-table-column prop="price" label="现价/元" align="center" width="80" />
                            <el-table-column label="团购价格/元" align="center" width="80" prop="skuGroupShopPrice" />
                            <el-table-column label="操作" align="center" width="100">
                                <template #default="scope">
                                    <el-button type="primary"
                                        @click="handlUpdate(scope.row, scope.$index)">更新</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                </el-drawer>
                <!-- 更新弹出框-->
                <el-dialog v-model="dialogVisible" title="更新团购价格" width="30%">
                    <el-form :model="priceForem">
                        <!-- 更新价格赋值给商品详情 表格渲染-->
                        <el-form-item label="团购价格" :label-width="100">
                            <!-- 数字输入框 -->
                            <el-input-number v-model="priceForem.groupPrice" class="mx-4" :min="1"
                                controls-position="right" />元
                        </el-form-item>
                        <el-form-item label="现价" :label-width="76" prop="price" v-model="editGroupsForm.price">
                            {{ editGroupsForm.price }}
                        </el-form-item>
                        <el-form-item label="sku类型名" :label-width="112" prop="title" v-model="editGroupsForm.title">
                            {{ editGroupsForm.title }}
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <!-- 更新确定按钮 -->
                            <el-button type="primary" @click="editComfirm">
                                确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>
  
<script lang="ts" setup>
import type { User, groups, prices, groupTable } from '@/type/params'//引入类型
import { ref, onMounted, reactive } from 'vue'//引入响应式，生命周期
import { Search, Plus } from '@element-plus/icons-vue'//引入图标
import { post } from '@/untils/request'//引入请求方式
import Pagination from '@/components/Pagination.vue' //引入分页组件
import { couponDates } from '@/time/friendlTime'//引入友好日期
import { ElMessage } from 'element-plus'//引入消息提示框

const title = ref<string>('')
const childBorder = ref(true)
const groupData = ref([])//团购列表
const productList = ref([])//弹框--团购商品列表
const detailsData = ref<groupTable[]>([])//商品详情列表
const dialogVisible = ref(false)//更新弹框，默认隐藏状态
const datas = ref({//渲染页面数据
    _gp: 'admin.groupshop',
    _mt: 'list',
    status: undefined,//团购状态
    id: '',//团购id
    spuId: undefined,//商品id
    spuName: '',//搜索关键字
    total: 0,//总条数
    page: 1,//当前页面
    limit: 10,//一页面所显示的条数
})
//团购状态
const groupStatusMap = [
    { value: 0, name: '冻结' },
    { value: 1, name: '激活' },
]
//抽屉状态--默认隐藏
const drawer = ref(false)
const formLabelWidth = '140px'
const visible = ref(false)
//表单数据
const form = ref<groups>({
    id: '',
    spuId: undefined,//商品id
    automaticRefund: 0,//未满策略
    gmtStart: '',//开始时间
    gmtEnd: '',//结束时间
    minNum: undefined,
    groupShopSkuList: []
})

//清空后的表单数据
const clearForm = ref<groups>({
    spuId: undefined,//商品id
    automaticRefund: 0,//未满策略
    gmtStart: '',//开始时间
    gmtEnd: '',//结束时间
    minNum: undefined,
    groupShopSkuList: []
})
//弹框更新--表单数据
const editGroupsForm = ref<prices>({
    skuGroupShopPrice: 1,//团购价格
    price: 0,//现价
    title: '',//sku类型名
    index: 0,//下标
    num: 0
})
//更新--团购价格
const priceForem = ref({
    groupPrice: 0
})

//生命周期---挂载后
onMounted(() => {
    init()
})
//渲染
function init() {
    post(datas.value).then(res => {//渲染团购商品列表
        // let { items } = res.data
        let { data } = res
        groupData.value = res.data//赋值
        datas.value.total = res.data.total//赋值总条数
        groupData.value.map((item: any) => {//映射显示优惠劵结束与开始时间
            if (item.gmtEnd < new Date().getTime()) {
                item.status = -1
            }
            item.gmtStart = item.gmtStart ? couponDates(item.gmtStart) : '无'
            item.gmtEnd = item.gmtEnd ? couponDates(item.gmtEnd) : '无'
            return item
        })
    }).catch(err => {
        console.log(err);
    })
    const products = reactive({
        _gp: 'admin.product',
        _mt: 'getSpuBigTree',
    })
    post(products).then(res => {//渲染类目列表
        productList.value = res.data
    }).catch(err => {
        console.log(err);

    })

}
//分页
function handlePagehange(s: { page: number, limit: number }) {
    datas.value.spuName = ''
    datas.value.status = undefined
    datas.value.page = s.page
    datas.value.limit = s.limit
    init()
}
//数据处理商品详情列表--截取商品详情id
function changeDetails(spuId: any) {
    const details = reactive({
        _gp: 'admin.product',
        _mt: 'detail',
        spuId
    })
    post(details).then(res => {//渲染商品详情列表
        detailsData.value = res.data.skuList
        detailsData.value.forEach((item: any) => {
            item['skuId'] = item['id']
        })
    }).catch(err => {
        console.log(err);

    })
}

//添加
function add() {
    title.value = '创建'
    drawer.value = true//显示抽屉
    Object.assign(form.value, clearForm.value)//合并表单数据与清空后的表单数据
}
//编辑
function handlEdit(row: User) {
    title.value = '编辑'
    Object.assign(form.value, row)
    drawer.value = true//显示抽屉
    detailsData.value = JSON.parse(JSON.stringify(row.groupShopSkuDTOList))
    console.log(form.value.groupShopSkuList, 1111);

}
// 抽屉确定按钮
function yes() {
    // 非空验证
    if (form.value.gmtStart >= form.value.gmtEnd) {
        return ElMessage.error('结束时间不能小于开始时间')
    }
    if (form.value.spuId == undefined) {
        return ElMessage.error('团购商品不能为空!')
    }
    if (form.value.minNum == undefined) {
        return ElMessage.warning('团购基础人数不能为空!')
    }

    form.value.gmtStart = new Date(form.value.gmtStart).getTime()
    form.value.gmtEnd = new Date(form.value.gmtEnd).getTime()
    const groupShopSkuList = JSON.stringify(detailsData.value)
    post({
        _gp: 'admin.groupshop',
        _mt: form.value.id != 0 ? 'edit' : 'create',
        ...form.value,
        groupShopSkuList
    }).then(res => {
        console.log(res)
        let { errno, errmsg } = res
        if (200 === errno) {
            init()
            ElMessage.success(form.value.id != 0 ? '编辑团购商品成功！' : '创建团购商品成功！')
            drawer.value = false//隐藏抽屉
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => console.log(err))
}
//取消--隐藏抽屉
function closeClick() {
    drawer.value = false
}
//批量定价--弹出框
function handlePrice() {
    visible.value = true//显示批量定价弹出框 
}
//批量定价--确定按钮
function groupPriceYes() {
    detailsData.value.forEach((item: any) => {
        item.skuGroupShopPrice = editGroupsForm.value.num
    });
    // priceForem
    editGroupsForm.value.num = ''//清空团购价格的历史记录
    visible.value = false//隐藏批量定价弹出框 

}

//更新--弹出框
function handlUpdate(row: User, index: number,) {
    dialogVisible.value = true//显示更新弹出框
    Object.assign(editGroupsForm.value, row)
    editGroupsForm.value.index = index
}
//更新-确定按钮
function editComfirm() {
    if (editGroupsForm.value.skuGroupShopPrice >= editGroupsForm.value.price) {
        return ElMessage.warning('团购价格必须小于现价！')
    }
    detailsData.value[editGroupsForm.value.index].skuGroupShopPrice = priceForem.value.groupPrice
    dialogVisible.value = false//隐藏更新弹出框
}
//删除
function handlDelt(index: number, row: User) {
    console.log(row);
    const datasDlet = {//删除角色管理数据
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id,//赋值id给当前商品id
    }
    //@ts-ignore
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    )
        .then(() => {

            post(datasDlet).then(res => {
                let { errno, errmsg } = res
                if (200 == errno) {
                    console.log(res);
                    groupData.value.splice(index, 1)//删除当前行
                    ElMessage.success('删除成功')
                    init()
                } else {
                    ElMessage.error(errmsg)
                }
            }).catch(err => {
                console.log(err);
                ElMessage.info('删除失败')
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })

}
</script>
<style lang="less" scoped>
.el-container {
    .btn {
        width: 100%;
        display: flex;

        .inp {
            width: 200px;
            margin-right: 15px;
        }
    }

    .btn,
    #tab {
        margin-bottom: 20px;
    }

    #tab {
        .pic {
            img {
                width: 30px;
                height: 30px;
                vertical-align: middle;
            }
        }
    }

    &::v-deep .el-drawer__body {
        padding: 0;
    }

    &::v-deep .el-card__body {
        padding: 0;
    }

    &::v-deep .el-drawer__header {
        margin-bottom: 0;
    }
}
</style>
<style>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.box-card {
    z-index: 1200;
    width: 50vw;
    padding: 0;
    position: relative;
    top: -20px;
}
</style>
